package com.easy.frame.base.service.mp.dataauth.config;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.easy.frame.base.service.mp.dataauth.component.DataAuthInterceptor;
import com.easy.frame.base.service.mp.dataauth.component.DataAuthSqlInjector;
import com.easy.frame.base.service.mp.dataauth.component.DataAuthStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * 数据权限配置类
 *
 * @author zzf
 * @date 2021/2/19 15:55
 */
@Slf4j
public abstract class AbstractDataAuthConfig {

    /**
     * 自定义的数据权限限制的处理策略
     */
    private static DataAuthStrategy dataAuthStrategy;

    /**
     * 初始化数据权限缓存数据
     */
    @PostConstruct
    public void init() {
        handlerConfigInit();
    }

    /**
     * 如果存在拦截器链Bean对象，
     */
    @ConditionalOnBean(Interceptor.class)
    @Configuration
    public static class InterceptorExists {

        @Autowired
        MybatisPlusInterceptor interceptor;

        /**
         * 获取并注册分页拦截器
         */
        @PostConstruct
        void addInterceptor() {
            DataAuthInterceptor dataAuthInterceptor = new DataAuthInterceptor(dataAuthStrategy);
            interceptor.addInnerInterceptor(dataAuthInterceptor);
        }
    }

    /**
     * 如果不存在拦截器链Bean，则我们注册
     */
    @Bean
    @ConditionalOnMissingBean(Interceptor.class)
    MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        DataAuthInterceptor dataAuthInterceptor = new DataAuthInterceptor(dataAuthStrategy);

        mybatisPlusInterceptor.addInnerInterceptor(dataAuthInterceptor);
        return mybatisPlusInterceptor;
    }

    /**
     * 使用数据权限限制的sql扫描器
     */
    @Bean
    ISqlInjector sqlInjector() {
        return new DataAuthSqlInjector();
    }


    protected AbstractDataAuthConfig(DataAuthStrategy dataAuthStrategy) {
        AbstractDataAuthConfig.dataAuthStrategy = dataAuthStrategy;
    }

    /**
     * 初始化数据权限缓存数据
     */
    protected abstract void handlerConfigInit();

}
